<?php

namespace App\Http\Resources\OpenShop\InvestmentPromotion;

use App\Enums\OpenShop\InvestmentPromotion\MainProcessEnum;
use App\Enums\OpenShop\InvestmentPromotion\SignOrderEnum;
use App\Enums\OpenShop\InvestmentPromotion\UserOrderEnum;
use App\Enums\OpenShop\MissionTemplateEnum;
use App\Library\Encrypt\Reversible;
use App\Http\Resources\BaseResource;
use App\Models\OpenShop\InvestmentPromotion\OpenShopMainProcessModel;
use App\Models\OpenShop\SiteLocation\OpenShopSiteLocationModel;
use App\Service\Common\ShortUrlService;
use Illuminate\Http\Request;

class OrderDetailResource extends BaseResource
{

    const M_DOMAIN_URL_PREFIX = 'order/sign/';

    /**
     * Transform the resource into an array.
     *
     * @param Request $request
     * @return array
     */
    public function toArray($request): array
    {
        $res = [
            'id'       => $this->id,
            'orderNo'  => $this->orderNo,
            'shopPattern'     => optional($this->siteLocationRel)->shopPattern,
            'shopPatternStr'  => optional($this->siteLocationRel)->shopPattern ? (OpenShopSiteLocationModel::SHOP_PATTERN_MAPPING[optional($this->siteLocationRel)->shopPattern] ?? '-') : '-',
            'patternType'     => (string)optional($this->siteLocationRel)->patternType,
            'patternTypeStr'  => OpenShopSiteLocationModel::getPatternTypeStr((string)optional($this->siteLocationRel)->patternType),
            'shopCode' => $this->kfShopCode,
            'shopId'   => (int)optional($this->progressRel)->shopId,
            'createAt' => $this->createdAt->timestamp > 0 ? date("Y-m-d H:i:s",
                $this->createdAt->timestamp) : '',
            'signTime' => $this->signTime > 0 ? date("Y-m-d H:i:s", $this->signTime) : '',

            'investmentManagerName'  => $this->investmentManagerName,
            'signUrl'                => ShortUrlService::addUrl(self::formatSignUrl($this->orderNo))['shortUrl'],
            'statusText'             => SignOrderEnum::ORDER_STATUS[$this->status],
//            'signStatus'             => self::getProgressText($this->progressRel->step, $this->getChildStep()),
            'signStatus'             => MissionTemplateEnum::STEP_STATUS_TEXT[$this->progressRel->nowStepStatus] ?? '',
            'step'                   => $this->step,
            'payStatus'              => $this->payStatus,
            'status'                 => $this->status,
            "shouldPayPrice"         => $this->shouldPayPrice,
            'baseInfo'               => $this->resourceLoaded('baseInfoRel') ? BaseInfoDetailResource::collection([$this->baseInfoRel])
                                                                                                     ->getIterator()
                                                                                                     ->current() : null,
            'contract'               => $contract = $this->resourceLoaded('contractRel') ? UserContractResource::collection([$this->contractRel])
                                                                                                               ->getIterator()
                                                                                                               ->current() : null,
//            'invalidContract'        => $invalidContract = $this->resourceLoaded('invalidContractRel') ? UserContractResource::collection([$this->invalidContractRel])
//                                                                                                               ->getIterator()
//                                                                                                               ->current() : null,
            'identityCard'           => $this->resourceLoaded('identityCardRel') ? UserIdentityCardResource::collection([$this->identityCardRel])
                                                                                                           ->getIterator()
                                                                                                           ->current() : null,
            'experience'             => $this->resourceLoaded('userExperienceRel') ? UserExperienceResource::collection([$this->userExperienceRel])
                                                                                                           ->getIterator()
                                                                                                           ->current() : null,
            'childOrder'             => (int)optional($this->progressRel)->childOrder,
            'shopNum'                => (int)optional($this->contractRel)->shopCount,
            'relationOrderNos'       => $this->progressRel->getRelationsOrderNos(),
            'isConfirm'              => ($this->step < SignOrderEnum::STEP_2) ? '合同待完善' : '',
            'isDisclosure'           => $this->disclosureStatus ? '' : '信息披露单待完善',
            'provideShopCode'        => $this->provideShopCode,
            'childLocationOrder'     => (int)optional($this->progressRel)->childLocationOrder,
            'childLocationOrderList' => $this->progressRel->getRelationsLocationOrderNos(),
            'nowStepStatus'          => $this->progressRel->nowStepStatus,
        ];

        // 是否展示『生成合同』按钮 1展示 0不展示
        if ($this->progressRel->childOrder == MainProcessEnum::CHILD_ORDER_1 && $this->step == SignOrderEnum::STEP_4 && !($contract->contractExtNo ?? '')) {
            $res['showCreateContract'] = 1;
        } else {
            $res['showCreateContract'] = 0;
        }

        return $res;
    }

    public function getChildStep()
    {
        $step = 0;
        switch ($this->progressRel->step) {
            case MainProcessEnum::MAIN_PROCESS_INVESTMENT_SIGN:
                $step = $this->step;
                break;
            case MainProcessEnum::MAIN_PROCESS_SHOP_LOCATION:
                $step = $this->shopLocationRel->step;
                break;
            case MainProcessEnum::MAIN_PROCESS_SPACE_DESIGN:
                $step = $this->progressRel->spaceDesignRel->step;
                break;
            case MainProcessEnum::MAIN_PROCESS_ENGINEER_CONSTRUCT:
                $step = $this->progressRel->engineeringConstructionRel->step;
                break;
            case MainProcessEnum::MAIN_PROCESS_SHOP_CHECK:
                $step = $this->progressRel->checkAcceptRel->step;
                break;
            case MainProcessEnum::MAIN_PROCESS_START_BUSINESS:
                $step = $this->progressRel->startBusinessRel->step;
                break;
        }
        return (int)$step;
    }

    /**
     * @param int $mainStep
     * @param int $step
     * @return string
     */
    public static function getProgressText(int $mainStep, int $step): string
    {
        $statusText = "";
        switch ($mainStep) {
            case MainProcessEnum::MAIN_PROCESS_INVESTMENT_SIGN:
                switch ($step) {
                    case UserOrderEnum::STEP_GENERATE_USER_INFO:
                    case UserOrderEnum::STEP_GENERATE_CONTRACT:
                    case UserOrderEnum::STEP_PART_PAID:
                        $statusText = "待支付";
                        break;
                    case UserOrderEnum::STEP_FINISH_PAID:
                        $statusText = "待签署";
                        break;
                    case UserOrderEnum::STEP_FINISH_CONTRACT:
                        $statusText = "已完成";
                        break;
                }
                break;
            case MainProcessEnum::MAIN_PROCESS_SHOP_LOCATION:
                switch ($step) {
                    case MainProcessEnum::SHOP_LOCATION_ASSIGN_MANAGER:
                        $statusText = "选址待提交";
                        break;
                    case MainProcessEnum::SHOP_LOCATION_FORM_SUBMIT:
                        $statusText = "商家待确认";
                        break;
                    case MainProcessEnum::SHOP_LOCATION_CONFIRM:
                        $statusText = "商家已确认";
                        break;
                    default:
                        $statusText = "开发待指派";
                        break;
                }
                break;
            case MainProcessEnum::MAIN_PROCESS_SPACE_DESIGN:
                $statusText = MainProcessEnum::MAIN_PROCESS_SPACE_DESIGN_MAP[$step] ?? '';
                break;
            case MainProcessEnum::MAIN_PROCESS_ENGINEER_CONSTRUCT:
                switch ($step) {
                    case MainProcessEnum::ENGINEER_CONSTRUCT_STAY:
                        $statusText = "进场待确认";
                        break;
                    case MainProcessEnum::ENGINEER_CONSTRUCT_START:
                        $statusText = "施工待完成";
                        break;
                    case MainProcessEnum::ENGINEER_CONSTRUCT_CONFIRM_FINISH:
                        $statusText = "已完成";
                        break;
                }
                break;
            case MainProcessEnum::MAIN_PROCESS_SHOP_CHECK:
                switch ($step) {
                    case MainProcessEnum::SHOP_CHECK_ASSIGN_MANAGER_STAY:
                        $statusText = "督导待指派";
                        break;
                    case MainProcessEnum::SHOP_CHECK_ASSIGN_MANAGER:
                        $statusText = "督导待验收";
                        break;
                    case MainProcessEnum::SHOP_CHECK_BY_MANAGER:
                        $statusText = "已完成";
                        break;
                }
                break;
            case MainProcessEnum::MAIN_PROCESS_START_BUSINESS:
                switch ($step) {
                    case MainProcessEnum::START_BUSINESS_STAY:
                        $statusText = "开业报告待提交";
                        break;
                    case MainProcessEnum::START_BUSINESS_SUBMIT:
                        $statusText = "已完成";
                        break;
                }
                break;
        }

        return vsprintf("%s (%s)", [
                MainProcessEnum::MAIN_PROCESS_MAP[$mainStep],
                $statusText
            ]
        );
    }

    // 加密
    public static function formatSignUrl(string $orderNo): string
    {
        //DES加密   URL加密
//        $url = urlencode(openssl_encrypt($orderNo, config('open-shop.encrypt-type'), config('open-shop.secretKey')));
        $url = Reversible::encode($orderNo);
        return config('open-shop.m') . self::M_DOMAIN_URL_PREFIX . $url;
    }

    // 解密
    public static function decodeSignUrl(string $code): string
    {
//        return openssl_decrypt(urldecode($code), config('open-shop.encrypt-type'), config('open-shop.secretKey'));
        return Reversible::decode($code);
    }
}
